<template>
  <div class="ai-chat-container">
    <!-- 顶部导航栏 -->
    <div class="chat-header-nav">
      <el-button 
        type="primary" 
        :icon="HomeFilled" 
        @click="goToHome"
        size="small"
      >
        返回首页
      </el-button>
      <h2 class="page-title">AI 聊天助手</h2>
    </div>
    
    <!-- 模型选择 -->
    <div class="model-selector">
      <el-select 
        v-model="selectedModel" 
        placeholder="选择AI模型" 
        size="small"
        @change="handleModelChange"
        class="model-select"
      >
        <el-option label="智普AI (GLM)" value="zhipu"></el-option>
        <el-option label="阿里云AI (Qwen)" value="aliyun"></el-option>
      </el-select>
      <!-- 阿里云子模型选择 -->
      <el-select 
        v-if="selectedModel === 'aliyun'"
        v-model="selectedAliyunModel" 
        placeholder="选择阿里云模型" 
        size="small"
        @change="handleAliyunModelChange"
        class="model-select"
      >
        <el-option label="Qwen-VL-Plus (视觉理解)" value="qwen-vl-plus"></el-option>
        <el-option label="Qwen-Plus (文本理解)" value="qwen-plus"></el-option>
      </el-select>
      <div class="model-info" v-if="selectedModel === 'zhipu'">
        当前使用: 智普AI GLM-4.5V 模型
      </div>
      <div class="model-info" v-else-if="selectedAliyunModel === 'qwen-vl-plus'">
        当前使用: 阿里云AI Qwen-VL-Plus 模型 (支持图片分析)
      </div>
      <div class="model-info" v-else>
        当前使用: 阿里云AI Qwen-Plus 模型
      </div>
    </div>
    
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="message in messages" 
        :key="message.id" 
        :class="['message', message.role]"
      >
        <div class="message-content">
          <div class="avatar">
            <el-icon v-if="message.role === 'user'"><User /></el-icon>
            <el-icon v-else><Robot /></el-icon>
          </div>
          <div class="text">
            <!-- 显示图片 -->
            <div v-if="message.imageUrl" class="image-preview">
              <img :src="message.imageUrl" alt="上传的图片" class="uploaded-image" />
            </div>
            <!-- 显示文本内容 -->
            <div class="content" v-html="formatMessage(message.content)"></div>
            <div class="timestamp">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>
      
      <!-- AI正在回答的加载状态 -->
      <div v-if="isLoading" class="message assistant loading-message">
        <div class="message-content">
          <div class="avatar">
            <el-icon class="rotating"><Robot /></el-icon>
          </div>
          <div class="text">
            <div class="loading-dots">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
            <div class="loading-text">AI正在思考中...</div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="chat-input" :class="{ loading: isLoading }">
      <!-- 图片上传区域 -->
      <div class="image-upload" v-if="showImageUpload">
        <el-upload
          class="image-uploader"
          drag
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handleImageUpload"
          :before-upload="beforeImageUpload"
          accept="image/*"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将图片拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              仅支持图片文件，且不超过10MB
            </div>
          </template>
        </el-upload>
      </div>
      
      <!-- 已选择图片预览 -->
      <div class="selected-image-preview" v-if="imageUrl && !showImageUpload">
        <div class="preview-container">
          <img :src="imageUrl" alt="已选择的图片" class="preview-img" />
          <el-button 
            class="remove-image-btn" 
            circle 
            size="small" 
            type="danger"
            @click="removeImage"
          >
            ×
          </el-button>
        </div>
        <span class="preview-tip">已选择图片，可以发送消息</span>
      </div>
      
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        placeholder="请输入您的问题..."
        @keydown.enter.exact.prevent="sendMessage"
        :disabled="isLoading"
      />
      <div class="input-actions">
        <el-button 
          type="primary" 
          @click="sendMessage" 
          :loading="isLoading"
          :disabled="(!inputMessage.trim() && !imageFile) || isLoading"
        >
          {{ isLoading ? '发送中...' : '发送' }}
        </el-button>
        <el-button @click="toggleImageUpload" :disabled="isLoading">
          {{ showImageUpload ? '取消图片' : '添加图片' }}
        </el-button>
        <el-button @click="clearChat" :disabled="isLoading">清空记录</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { User, ChatDotRound as Robot, UploadFilled, HomeFilled } from '@element-plus/icons-vue';
import { sendAIMessage, uploadFile } from '@/api/ai';

const router = useRouter();

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: Date;
  imageUrl?: string; // 添加图片URL字段
}

const messages = ref<Message[]>([
  {
    id: '1',
    role: 'assistant',
    content: '您好！我是AI助手，您可以向我提问任何问题，我会尽力为您解答。',
    timestamp: new Date()
  }
]);

const inputMessage = ref('');
const isLoading = ref(false);
const messagesContainer = ref<HTMLElement | null>(null);
// 添加图片上传相关状态
const showImageUpload = ref(false);
const imageFile = ref<File | null>(null);
const imageUrl = ref<string | null>(null);
// 添加模型选择相关状态
const selectedModel = ref('zhipu'); // 默认使用智普模型
// 添加阿里云子模型选择相关状态
const selectedAliyunModel = ref('qwen-vl-plus'); // 默认使用支持视觉理解的模型

// 格式化消息内容
const formatMessage = (content: string) => {
  // 处理换行符和其他特殊字符
  if (!content) return '';
  
  // 将换行符转换为HTML换行标签
  let formattedContent = content.replace(/\n/g, '<br>');
  
  // 处理多个连续的空格
  formattedContent = formattedContent.replace(/ {2}/g, '&nbsp;&nbsp;');
  
  return formattedContent;
};

// 格式化时间
const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  });
};

// 滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 切换图片上传区域显示
const toggleImageUpload = () => {
  showImageUpload.value = !showImageUpload.value;
  console.log('切换图片上传区域显示:', showImageUpload.value);
  // 如果关闭图片上传，清空已选择的图片
  if (!showImageUpload.value) {
    imageFile.value = null;
    imageUrl.value = null;
  }
};

// 移除已选择的图片
const removeImage = () => {
  imageFile.value = null;
  imageUrl.value = null;
  ElMessage.info('已取消图片选择');
};

// 图片上传前的处理
const beforeImageUpload = (file: File) => {
  console.log('图片上传前处理:', file);
  const isImage = file.type.startsWith('image/');
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过10MB!');
    return false;
  }
  
  // 保存文件引用
  imageFile.value = file;
  console.log('保存文件引用到imageFile.value:', file);
  
  // 生成预览URL
  const reader = new FileReader();
  reader.onload = (e) => {
    imageUrl.value = e.target?.result as string;
    console.log('生成预览URL:', imageUrl.value);
  };
  reader.readAsDataURL(file);
  
  return false; // 不自动上传
};

// 处理图片上传
const handleImageUpload = (file: any) => {
  console.log('处理图片上传:', file);
  // 文件已经在beforeImageUpload中处理了
  // 但为了确保兼容性，我们在这里也处理一下
  if (file && file.raw) {
    // 保存文件引用
    imageFile.value = file.raw;
    console.log('保存文件引用到imageFile.value (来自file.raw):', file.raw);
    
    // 生成预览URL
    const reader = new FileReader();
    reader.onload = (e) => {
      imageUrl.value = e.target?.result as string;
      console.log('生成预览URL (来自handleImageUpload):', imageUrl.value);
      
      // 图片选择后自动隐藏上传区域
      showImageUpload.value = false;
      ElMessage.success('图片已选择，可以发送消息了');
    };
    reader.readAsDataURL(file.raw);
  }
  return false;
};

// 处理HTTP请求（Element Plus上传组件需要）
const handleHttpRequest = (options: any) => {
  console.log('处理HTTP请求:', options);
  // 这个函数不会被实际调用，因为我们设置了auto-upload=false
  // 但它需要存在以避免类型错误
  return Promise.resolve();
};

// 上传图片到服务器
const uploadImageToServer = async (file: File): Promise<string> => {
  try {
    console.log('开始上传文件到服务器:', file);
    
    // 显示上传提示
    ElMessage.info('正在上传图片...');
    
    const response: any = await uploadFile(file, 'AI聊天');
    console.log('文件上传响应:', response);
    
    // 响应拦截器已经处理了响应，直接检查response.code
    if (response.code !== 200) {
      console.error('文件上传失败，错误码:', response.code, '错误信息:', response.message);
      throw new Error(response.message || '文件上传失败');
    }
    
    // 上传成功提示
    ElMessage.success('图片上传成功');
    
    // 返回上传后的文件URL
    // 确保返回的是完整的访问URL
    if (response.data && response.data.accessUrl) {
      console.log('成功获取图片URL:', response.data.accessUrl);
      return response.data.accessUrl;
    }
    
    console.error('文件上传响应中未找到accessUrl:', response);
    return '';
  } catch (error) {
    console.error('文件上传错误:', error);
    throw error;
  }
};

// 发送消息
const sendMessage = async () => {
  console.log('开始发送消息，当前状态:', {
    hasInputMessage: !!inputMessage.value.trim(),
    hasImageFile: !!imageFile.value,
    imageFile: imageFile.value,
    isLoading: isLoading.value
  });
  
  if ((!inputMessage.value.trim() && !imageFile.value) || isLoading.value) return;
  
  // 构建用户消息
  const userMessage: Message = {
    id: Date.now().toString(),
    role: 'user',
    content: inputMessage.value.trim(),
    timestamp: new Date(),
    imageUrl: imageUrl.value || undefined
  };
  
  // 添加用户消息
  messages.value.push(userMessage);
  
  // 清空输入框
  const userContent = inputMessage.value.trim();
  inputMessage.value = '';
  
  // 设置加载状态
  isLoading.value = true;
  
  try {
    // 滚动到最新消息
    scrollToBottom();
    
    // 准备发送给后端的数据
    let requestData: any = {
      message: userContent,
      modelType: selectedModel.value // 添加模型类型参数
    };
    
    // 如果是阿里云模型，添加具体的子模型类型
    if (selectedModel.value === 'aliyun') {
      requestData.aliyunModel = selectedAliyunModel.value;
    }
    
    console.log('准备上传图片，imageFile.value:', imageFile.value);
    
    // 如果有图片，上传图片并获取URL
    if (imageFile.value) {
      console.log('开始上传图片:', imageFile.value);
      const uploadedImageUrl = await uploadImageToServer(imageFile.value);
      console.log('图片上传完成，获得URL:', uploadedImageUrl);
      requestData.imageUrl = uploadedImageUrl;
    } else {
      console.log('没有图片需要上传');
    }
    
    console.log('发送到后端的数据:', requestData);
    
    // 调用后端API
    const response: any = await sendAIMessage(requestData);
    
    console.log('后端响应:', response);
    
    // 根据响应拦截器的逻辑，成功的响应直接返回data
    // 需要检查response.code是否为200
    if (response.code !== 200) {
      throw new Error(response.message || 'API请求失败');
    }
    
    // 正确提取AI回复内容
    // 根据后端AIController的实现，返回的是Result.success("请求成功", aiResponse)
    // 响应拦截器会返回{code: 200, message: "请求成功", data: aiResponse}
    // 所以response.data就是AI的回复内容
    const aiContent = response.data || '抱歉，我没有理解您的问题。';
    
    const aiMessage: Message = {
      id: Date.now().toString(),
      role: 'assistant',
      content: aiContent,
      timestamp: new Date()
    };
    
    // 添加AI回复
    messages.value.push(aiMessage);
  } catch (error: any) {
    console.error('AI聊天错误:', error);
    
    // 提供更友好的错误提示
    let errorMessage = 'AI助手回复失败，请稍后重试';
    if (error.code === 'ECONNABORTED' || (error.message && error.message.includes('timeout'))) {
      errorMessage = 'AI助手处理时间较长，请稍后重试';
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    ElMessage.error(errorMessage);
    
    const errorMessageObj: Message = {
      id: Date.now().toString(),
      role: 'assistant',
      content: '抱歉，我遇到了一些问题，请稍后重试。',
      timestamp: new Date()
    };
    
    messages.value.push(errorMessageObj);
  } finally {
    // 在finally块中清空图片状态，确保即使出错也能清空
    console.log('清空图片状态');
    imageFile.value = null;
    imageUrl.value = null;
    showImageUpload.value = false;
    isLoading.value = false;
    scrollToBottom();
  }
};

// 清空聊天记录
const clearChat = () => {
  messages.value = [
    {
      id: '1',
      role: 'assistant',
      content: '您好！我是AI助手，您可以向我提问任何问题，我会尽力为您解答。',
      timestamp: new Date()
    }
  ];
};

// 处理模型切换
const handleModelChange = (model: string) => {
  console.log('切换AI模型:', model);
  ElMessage.info(`已切换到${model === 'zhipu' ? '智普AI' : '阿里云AI'}模型`);
};

// 处理阿里云子模型切换
const handleAliyunModelChange = (model: string) => {
  console.log('切换阿里云子模型:', model);
  ElMessage.info(`已切换到阿里云AI ${model} 模型`);
};

// 返回首页
const goToHome = () => {
  router.push('/');
};

// 组件挂载后滚动到底部
onMounted(() => {
  scrollToBottom();
});
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 顶部导航栏样式 */
.chat-header-nav {
  padding: 15px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  gap: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.page-title {
  margin: 0;
  color: white;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
}

.model-selector {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  background: #f8fafc;
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.model-select {
  width: 180px;
}

.model-info {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.chat-header h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
}

.chat-header p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8fafc;
}

.message {
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease-in;
}

.message-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.message.user .message-content {
  flex-direction: row-reverse;
}

.message.user .text {
  background: #667eea;
  color: white;
  border-radius: 18px 4px 18px 18px;
}

.message.assistant .text {
  background: #fff;
  color: #333;
  border: 1px solid #eee;
  border-radius: 4px 18px 18px 18px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #667eea;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  color: white;
}

.message.user .avatar {
  background: #764ba2;
}

.text {
  max-width: 80%;
  padding: 12px 16px;
}

.content {
  line-height: 1.5;
  font-size: 14px;
  white-space: pre-wrap;
}

.timestamp {
  margin-top: 8px;
  font-size: 12px;
  opacity: 0.7;
  text-align: right;
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #eee;
  background: #fff;
  transition: opacity 0.3s ease;
}

.chat-input.loading {
  opacity: 0.6;
  pointer-events: none;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 12px;
}

/* 图片上传相关样式 */
.image-upload {
  margin-bottom: 15px;
}

/* 已选择图片预览 */
.selected-image-preview {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 8px;
  border: 1px dashed #dcdfe6;
}

.preview-container {
  position: relative;
  display: inline-block;
  margin-bottom: 8px;
}

.preview-img {
  max-width: 150px;
  max-height: 150px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: block;
}

.remove-image-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  padding: 0;
  font-size: 18px;
  line-height: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.preview-tip {
  display: block;
  font-size: 12px;
  color: #67c23a;
  margin-top: 8px;
}

.image-preview {
  margin-bottom: 10px;
}

.uploaded-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 加载状态样式 */
.loading-message {
  animation: fadeIn 0.3s ease-in;
}

.loading-message .text {
  background: #fff;
  color: #333;
  border: 1px solid #eee;
  border-radius: 4px 18px 18px 18px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  padding: 16px 20px;
}

.rotating {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.loading-dots {
  display: flex;
  gap: 6px;
  margin-bottom: 8px;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #667eea;
  animation: bounce 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.loading-text {
  font-size: 13px;
  color: #666;
  font-style: italic;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .chat-header {
    padding: 15px;
  }
  
  .chat-header h2 {
    font-size: 18px;
  }
  
  .chat-messages {
    padding: 15px;
  }
  
  .text {
    max-width: 90%;
    padding: 10px 14px;
  }
  
  .chat-input {
    padding: 15px;
  }
  
  .uploaded-image {
    max-width: 150px;
    max-height: 150px;
  }
}
</style>